﻿namespace AnyOffice.WebControls
{
    using System;
    using System.Data;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    public class DropDownListColumn : ITemplate
    {
        private string dataValue;
        private DataView dataView;
        private string dispalyText;
        private string id = "1";
        private string selField;

        public DropDownListColumn(string disTxt, string dValue, DataView dataSource, string selectedField)
        {
            this.dispalyText = disTxt;
            this.dataValue = dValue;
            this.dataView = dataSource;
            this.selField = selectedField;
        }

        private void grid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DropDownList list = (DropDownList) e.Row.FindControl(this.id);
                list.Items.FindByValue(Convert.ToString(DataBinder.Eval(e.Row.DataItem, this.selField))).Selected = true;
            }
        }

        public void InstantiateIn(Control container)
        {
            DropDownList child = new DropDownList();
            child.ID = this.id;
            child.DataTextField = this.dispalyText;
            child.DataValueField = this.dataValue;
            child.DataSource = this.dataView;
            child.DataBind();
            child.DataBinding += new EventHandler(this.OnDataBinding);
            container.Controls.Add(child);
        }

        public void OnDataBinding(object sender, EventArgs e)
        {
            DropDownList list = (DropDownList) sender;
            GridViewRow namingContainer = (GridViewRow) list.NamingContainer;
            HFGridView parent = (HFGridView) namingContainer.Parent.Parent;
            parent.RowDataBound += new GridViewRowEventHandler(this.grid_RowDataBound);
        }
    }
}

